/*
 * KeyMapComboBoxModel.java
 *
 * Created on 19. Juli 2007, 21:46
 *
 * Copyright (c) 2007 Daniel Gronau
 *
 * This file is part of KanjiTori.
 *
 * KanjiTori is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * KanjiTori is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 *
 */

package kanjitori.preferences;

import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractListModel;
import javax.swing.ComboBoxModel;

/**
 *
 * @author Pirx
 */
public class KeyMapComboBoxModel extends AbstractListModel implements ComboBoxModel {
    
    private final static String EMPTY = "";
    private static List<KeyMapComboBoxModel> list = new ArrayList<KeyMapComboBoxModel>();
    
    private String action;
    private String key;
    private int pos;
    
    /** Creates a new instance of KeyMapComboBoxModel */
    public KeyMapComboBoxModel(String action, int pos) {
        this.action = action;
        this.pos = pos;
        list.add(this);
        reInitialize();
    }
    
    private void reInitialize() {
        List<String> keyList = KeyMap.getKeys(action);
        if (pos < keyList.size()) {
            key = keyList.get(pos);
        }
        setSelectedItem(key);
    }
    
    public static void reInit() {
        for (KeyMapComboBoxModel model : list) {
            model.reInitialize();
        }
    }
    
    public int getSize() {
        return KeyMap.KEYS.length + 1;
    }
    
    public Object getElementAt(int index) {
        return index == 0 ? EMPTY : KeyMap.KEYS[index - 1];
    }
    
    public void setSelectedItem(Object anItem) {
        if (anItem == null) {
            anItem = EMPTY;
        }
        if (! EMPTY.equals(anItem)) {
           for (KeyMapComboBoxModel model : list) {
              if (anItem.equals(model.getSelectedItem()) && model != this) {
                  model.setSelectedItem(EMPTY);
              }
           }
        }
        key = anItem.toString();
        fireContentsChanged(this,0,getSize());
    }
    
    public Object getSelectedItem() {
        return key;
    }
    
    public static void save() {
        KeyMap.unbindAll();
        for (KeyMapComboBoxModel model : list) {
            if (model.key != EMPTY) {
                KeyMap.bind(model.key, model.action);
            }
        }
    }
}
